package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-04
 * Time: 17:09
 */
public class PrintABC {
    private int count = 1; // 控制打印的轮次
    private final int MAX_COUNT = 10; // 打印的总轮次

    public static void main(String[] args) {
        PrintABC abc = new PrintABC();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < abc.MAX_COUNT; ) {
                synchronized (abc) {
                    while (abc.count % 3 != 1) {
                        try {
                            abc.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("A ");
                    abc.count++;
                    abc.notifyAll();
                    i++;
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < abc.MAX_COUNT; ) {
                synchronized (abc) {
                    while (abc.count % 3 != 2) {
                        try {
                            abc.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B ");
                    abc.count++;
                    abc.notifyAll();
                    i++;
                }
            }
        });

        Thread t3 = new Thread(() -> {
            for (int i = 0; i < abc.MAX_COUNT; ) {
                synchronized (abc) {
                    while (abc.count % 3 != 0) {
                        try {
                            abc.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("C ");
                    abc.count++;
                    abc.notifyAll();
                    i++;
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
